package com.le.edu.controller;

import com.le.edu.domain.dto.LoginDTO;
import com.le.edu.domain.entity.User;
import com.le.edu.exception.AppException;
import com.le.edu.resp.Result;
import com.le.edu.resp.ResultCodeEnum;
import com.le.edu.service.UserService;
import com.le.edu.utils.ClientUtils;
import com.le.edu.utils.ConstUtils;
import com.le.edu.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Le
 * @create 2024-04-17 14:46
 */
@RestController
@RequiredArgsConstructor
@Tag(name = "用户登录接口")
public class LoginController {
    private final UserService userService;
    private final RedisTemplate<String, Object> redisTemplate;

    @Operation(summary = "登录")
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginDTO dto, HttpServletRequest request) {
        ClientUtils.ClientEnum clientEnum = ClientUtils.checkClientType(request);
        String token = userService.login(dto.getUsername(), dto.getPassword(), clientEnum);
        return Result.ok(token);
    }

    @Operation(summary = "获取用户详情信息")
    @GetMapping("/info")
    public Result<User> isLogin(HttpServletRequest request) {
        String token = request.getHeader(ConstUtils.TOKEN);
        Boolean flag = redisTemplate.hasKey(ConstUtils.USER_LOGIN_KEY + token);
        if (!flag) {
            throw new AppException(ResultCodeEnum.FORBIDDEN);
        }
        Long currentUserId = JwtUtils.getJSONObject(token);
        User user = userService.getById(currentUserId);
        return Result.ok(user);
    }

    @Operation(summary = "注销")
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        String token = request.getHeader(ConstUtils.TOKEN);
        redisTemplate.delete(ConstUtils.USER_LOGIN_KEY + token);
        return Result.ok();
    }
}
